﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Web.Routing;

namespace Coleotrack.Helper
{
    public static class HtmlExtensions
    {
        public static MvcHtmlString MenuItem(this HtmlHelper htmlHelper, string text, string action, string controller, RouteValueDictionary routeValues)
        {
            var menu = new TagBuilder("a");
            var currentAction = (string)htmlHelper.ViewContext.RouteData.Values["action"];
            var currentController = (string)htmlHelper.ViewContext.RouteData.Values["controller"];
            var currentArea = (string) htmlHelper.ViewContext.RouteData.DataTokens["area"];
            
            if (!string.IsNullOrEmpty(currentArea))
            {
                if (CheckArea(currentArea, routeValues))
                {
                    menu.AddCssClass("current");
                }
            }
            else
            {
                if (routeValues == null || !routeValues.ContainsKey("area") || string.IsNullOrEmpty(routeValues["area"].ToString()))
                {
                    if ((string.Equals(currentAction, action, StringComparison.CurrentCultureIgnoreCase) &&
                         string.Equals(currentController, controller, StringComparison.CurrentCultureIgnoreCase)))
                    {
                        menu.AddCssClass("current");
                    }
                }
            }

            var url = new UrlHelper(htmlHelper.ViewContext.RequestContext);
            menu.Attributes.Add("href", url.Action(action, controller, routeValues));

            menu.SetInnerText(text);
            return MvcHtmlString.Create(menu.ToString());
        }

        private static bool CheckArea(string currentArea, RouteValueDictionary routeValues)
        {
            if (currentArea == null)
            {
                return false;
            }

            if (routeValues == null)
            {
                routeValues = new RouteValueDictionary();
            }

            if (!routeValues.ContainsKey("area"))
            {
                routeValues.Add("area", string.Empty);
            }
            
            return currentArea.Equals(routeValues["area"]);
        }

        public static MvcHtmlString MenuItem(this HtmlHelper htmlHelper, string text, string action, string controller)
        {
            return MenuItem(htmlHelper, text, action, controller, null);
        }
    }
}